<template>
  <MainSlot>
    <template v-slot:searchForm>
      <SearchForm v-if="formItemList.length" :formItemList="formItemList" @search="(e) => {
        (searchlist = { ...e }), (currentPage = 1), getTableDataList();
      }
        ">
      </SearchForm>
    </template>
    <template v-slot:btn>
      <BtnSlot :btnList="btnList" @handleEvent="getBtnEvent"></BtnSlot>
    </template>
    <template v-slot:tab>
      <EnumSlot @handleEvent="getEnumEvent" :selectIndex="selectIndex" :enumList="enumList"></EnumSlot>
    </template>
    <template v-slot:table>
      <TableData :isSelect="true" :tableThead="tableThead" :dataList="dataList" @selection-change="selectionChange">
        <template v-slot:operation="{ row }">
          <template v-if="!row.index">
            <el-button v-if="codeList.indexOf('edit') !== -1 && forderStatus === 0" class="text-btn-cursor" type="text"
              size="small" @click="edit(row)">
              <i class="el-icon-edit-outline"></i> 修改
            </el-button>
            <el-button v-if="codeList.indexOf('revoke') !== -1 && forderStatus === 0" class="text-btn-cursor"
              type="text" size="small" @click="check(row)">
              <i class="el-icon-edit-outline"></i>审核
            </el-button>
            <el-button v-if="codeList.indexOf('delete') !== -1 && forderStatus === 0"
              class="text-btn-cursor cursor-delete" type="text" size="small" @click="handleDelete([row])">
              <i class="el-icon-delete"></i> 删除
            </el-button>
            <el-button v-if="forderStatus !== 0" class="text-btn-cursor" type="text" size="small" @click="check(row)">
              <i class="el-icon-view"></i>查看详情
            </el-button>
            <el-button v-if="forderStatus !== 0 && !row.completeStatus" class="text-btn-cursor" type="text" size="small"
              @click="completeStatus(row)">
              <i class="el-icon-view"></i>点击完成
            </el-button>
            <el-button v-if="forderStatus !== 0 && row.completeStatus" class="text-btn-cursor" type="text" size="small">
              <i class="el-icon-view"></i>已完成
            </el-button>
          </template>
        </template>
        <template v-slot:completeStatus="{ row }">
          <span v-if="item.prop === 'completeStatus'">{{
            row[item.prop] ? "完成" : "未完成"
          }}</span>
          <span v-else>{{ row[item.prop] || "——" }}</span>
        </template>
      </TableData>
    </template>
    <template v-slot:pagination>
      <Pagination @size-Change="changePageSize" :size="pageSize" @current-change="handleCurrentChange"
        :page="currentPage" :total="total">
      </Pagination>
    </template>
    <template v-slot:dialogModule>
      <el-dialog :close-on-click-modal="false" width="60%" :title="titleText" :visible.sync="dialogFormVisible"
        @close="cancel('formData')">
        <el-form ref="formData" label-position="left" :model="formData" :rules="rules" class="el-form">
          <!-- 添加 -->
          <el-form-item v-for="(item, index) in formDatalists" :key="index" :label="item.name + ':'"
            :prop="item.type === 'Select' ? item.selectValue : item.prop" class="w50p" :rules="item.isCheck
              ? rules[item.prop]
              : [
                {
                  required: item.required,
                  message: item.name + '不能为空',
                  trigger: item.type === 'input' ? 'blur' : 'change',
                },
              ]
              ">
            <el-input class="w100p" v-if="item.type === 'input'" v-model="formData[`${item.prop}`]"
              :placeholder="'请输入' + item.name" clearable :disabled="nowChanceStau === 'check' ||
                item.prop === 'orderNo' ||
                item.prop === 'totalNumber'
                " />
            <el-select v-if="item.type === 'Select'" v-model="formData[`${item.selectValue}`]" filterable
              :placeholder="'请选择' + item.name" clearable class="w100p" :disabled="nowChanceStau === 'check'"
              @change="getCoustomer($event, item.prop)">
              <el-option v-for="(items, indexs) in item.typeObj.list" :key="indexs" :label="items.name"
                :value="items.value" />
            </el-select>
            <el-date-picker v-if="item.type === 'TimePicker'" v-model="formData[`${item.prop}`]" type="datetime"
              class="w100p" value-format="yyyy-MM-dd HH:mm" :placeholder="'选择' + item.name"
              :disabled="nowChanceStau === 'check'" />
          </el-form-item>
          <el-divider content-position="left">采购订单明细</el-divider>
          <!-- 循环明细 -->
          <div v-for="(orderDetail, index) in formData.orderDetailList" :key="orderDetail.key" class="w100p xunhuan">
            <div class="w100p goods">采购商品{{ index + 1 }}</div>
            <el-form-item label="商品名称 :" :prop="'orderDetailList.' + index + '.materialNo'" class="w50p" :rules="[
              {
                required: true,
                message: '商品名称不能为空',
                trigger: 'change',
              },
            ]">
              <el-select v-model="orderDetail.materialNo" placeholder="请选择商品（物料）名称" clearable class="w100p"
                :disabled="nowChanceStau === 'check'" @change="getGoods($event, index)">
                <el-option v-for="(items, indexs) in materialList" :key="indexs" :label="items.materialName"
                  :value="items.materialNo" />
              </el-select>
            </el-form-item>
            <el-form-item label="收货仓库 :" :prop="'orderDetailList.' + index + '.stordocNo'" class="w50p">
              <el-select v-model="orderDetail.stordocNo" placeholder="请选择收货仓库" clearable class="w100p"
                :disabled="nowChanceStau === 'check'">
                <el-option v-for="(items, indexs) in stordocList" :key="indexs" :label="items.stordocName"
                  :value="items.stordocNo" />
              </el-select>
            </el-form-item>
            <el-form-item label="采购数量 :" :prop="'orderDetailList.' + index + '.confirmQuantity'" class="w50p" :rules="[
              { required: true, message: '数量不能为空', trigger: 'blur' },
              {
                pattern: /^\d+$/,
                message: '值该为正整数',
                trigger: ['change', 'blur'],
              },
            ]">
              <el-input v-model="orderDetail.confirmQuantity" clearable class="one" placeholder="请输入数量"
                :disabled="nowChanceStau === 'check'" @change="countOnePrice($event, index)" />
              <el-select v-model="orderDetail.castUnitNo" placeholder="请选择单位" class="two" clearable
                :disabled="nowChanceStau === 'check'">
                <el-option v-for="(items, indexs) in unitList" :key="indexs" :label="items.symbol || items.unitName"
                  :value="items.unitNo" />
              </el-select>
            </el-form-item>

            <el-form-item label="单位 :" :prop="'orderDetailList.' + index + '.castUnitNo'" class="w50p" :rules="[
              { required: true, message: '单位不能为空', trigger: 'change' },
            ]">
              <el-select v-model="orderDetail.castUnitNo" placeholder="请选择单位" clearable class="w100p"
                :disabled="nowChanceStau === 'check'">
                <el-option v-for="(items, indexs) in unitList" :key="indexs" :label="items.symbol || items.unitName"
                  :value="items.unitNo" />
              </el-select>
            </el-form-item>
            <el-form-item label="换算率 :" :prop="'orderDetailList.' + index + '.exchangeRate'" class="w50p" :rules="[
              {
                pattern:
                  /^([1-9]\d*(\.\d*[1-9][0-9])?)|(0\.\d*[1-9][0-9])|(0\.\d*[1-9])$/,
                message: '值为大于0的数',
                trigger: ['change', 'blur'],
              },
              {
                required: true,
                message: '换算率不能为空',
                trigger: 'change',
              },
            ]">
              <el-input v-model="orderDetail.exchangeRate" clearable class="w100p" placeholder="请输入换算率"
                :disabled="nowChanceStau === 'check'" />
            </el-form-item>
            <div class="zhu w50p">
              <el-form-item label="主数量&主单位 :" :prop="'orderDetailList.' + index + '.primaryQuantity'" style="width: 78%"
                :rules="[
                  { required: true, message: '数量不能为空', trigger: 'blur' },
                  {
                    pattern:
                      /^([1-9]\d*(\.\d*[1-9][0-9])?)|(0\.\d*[1-9][0-9])|(0\.\d*[1-9])$/,
                    message: '值为大于0的数',
                    trigger: ['change', 'blur'],
                  },
                ]">
                <el-input v-model="orderDetail.primaryQuantity" clearable disabled class="w100p" placeholder="请输入主数量" />
              </el-form-item>
              <el-form-item style="width: 18%" :prop="'orderDetailList.' + index + '.unitNo'" :rules="[
                {
                  required: true,
                  message: '主单位不能为空',
                  trigger: 'change',
                },
              ]">
                <el-select v-model="orderDetail.unitNo" placeholder="请选择单位" disabled clearable>
                  <el-option v-for="(items, indexs) in unitList" :key="indexs" :label="items.symbol || items.unitName"
                    :value="items.unitNo" />
                </el-select>
              </el-form-item>
            </div>
            <el-form-item label="单价/元 :" :prop="'orderDetailList.' + index + '.price'" class="w50p" :rules="[
              {
                pattern:
                  /^([1-9]\d*(\.\d*[1-9][0-9])?)|(0\.\d*[1-9][0-9])|(0\.\d*[1-9])$/,
                message: '值为大于0的数',
                trigger: ['change', 'blur'],
              },
              { required: true, message: '单价不能为空', trigger: 'change' },
            ]">
              <el-input v-model="orderDetail.price" clearable placeholder="请输入单价" :disabled="nowChanceStau === 'check'"
                @change="countOnePrice($event, index)" />
            </el-form-item>

            <el-form-item label="折扣/折 :" :prop="'orderDetailList.' + index + '.discount'" class="w50p" :rules="{
              pattern: /^\d(\.\d)?$/,
              message: '数字不能小于0大于10且只能有一位小数',
              trigger: ['change', 'blur'],
            }">
              <el-input v-model="orderDetail.discount" clearable :disabled="nowChanceStau === 'check'"
                placeholder="请输入数量" @change="countOnePrice($event, index)" />
            </el-form-item>

            <el-form-item label="折扣额/元 :" :prop="'orderDetailList.' + index + '.discountPrice'" class="w50p" :rules="[
              {
                pattern:
                  /^([1-9]\d*(\.\d*[1-9][0-9])?)|(0\.\d*[1-9][0-9])|(0\.\d*[1-9])$/,
                message: '值为大于0的数',
                trigger: ['change', 'blur'],
              },
            ]">
              <el-input v-model="orderDetail.discountPrice" :disabled="nowChanceStau === 'check'" clearable
                placeholder="请输入数量" />
            </el-form-item>

            <el-form-item label="件数 :" :prop="'orderDetailList.' + index + '.packNum'" class="w50p" :rules="[
              {
                pattern: /^\d+$/,
                message: '值该为正整数',
                trigger: ['change', 'blur'],
              },
              { required: true, message: '单价不能为空', trigger: 'change' },
            ]">
              <el-input v-model="orderDetail.packNum" clearable :disabled="nowChanceStau === 'check'"
                placeholder="请输入数量" />
            </el-form-item>

            <el-form-item label="价税合计/元 :" :prop="'orderDetailList.' + index + '.totalPrice'" class="w50p" :rules="[
              {
                pattern:
                  /^([1-9]\d*(\.\d*[1-9][0-9])?)|(0\.\d*[1-9][0-9])|(0\.\d*[1-9])$/,
                message: '值为大于0的数',
                trigger: ['change', 'blur'],
              },
              {
                required: true,
                message: '价税合计不能为空',
                trigger: 'change',
              },
            ]">
              <el-input v-model="orderDetail.totalPrice" clearable :disabled="nowChanceStau === 'check'"
                placeholder="请输入金额" />
            </el-form-item>

            <el-form-item label="体积/L :" :prop="'orderDetailList.' + index + '.volume'" class="w50p" :rules="[
              {
                pattern:
                  /^([1-9]\d*(\.\d*[1-9][0-9])?)|(0\.\d*[1-9][0-9])|(0\.\d*[1-9])$/,
                message: '值为大于0的数',
                trigger: ['change', 'blur'],
              },
            ]">
              <el-input v-model="orderDetail.volume" clearable :disabled="nowChanceStau === 'check'"
                placeholder="请输入体积" />
            </el-form-item>

            <el-form-item label="收货地址 :" :prop="'orderDetailList.' + index + '.address'" class="w50p" :rules="[
              {
                required: true,
                message: '收货地址不能为空',
                trigger: 'change',
              },
            ]">
              <el-select v-model="orderDetail.address" placeholder="请选择收货地址" clearable class="w100p"
                :disabled="nowChanceStau === 'check'">
                <el-option v-for="(items, indexs) in addressList" :key="indexs" :label="items.spliceAddress"
                  :value="items.spliceAddress" />
              </el-select>
            </el-form-item>
            <el-form-item label="预计到货时间 :" :prop="'orderDetailList.' + index + '.arrivalTime'" class="w50p">
              <el-date-picker v-model="orderDetail.arrivalTime" type="datetime" value-format="yyyy-MM-dd HH:mm"
                class="w100p" clearable placeholder="请选择时间" :disabled="nowChanceStau === 'check'" />
            </el-form-item>

            <el-form-item label="操作员 :" :prop="'orderDetailList.' + index + '.chandlerName'" class="w50p">
              <el-input v-model="orderDetail.chandlerName" clearable :disabled="nowChanceStau === 'check'"
                placeholder="请输入操作员" />
            </el-form-item>
            <div class="editBox">
              <el-button v-if="nowChanceStau === 'edit' && !orderDetail.orderNo" type="primary" @click="
                addDetail(
                  { ...orderDetail, orderNo: formData.orderNo },
                  index
                )
                ">添加</el-button>
              <el-button v-if="nowChanceStau === 'edit' && orderDetail.orderNo" type="warning"
                @click="editDetail(orderDetail)">修改</el-button>
              <el-button v-if="nowChanceStau === 'edit' && orderDetail.orderNo" type="danger"
                @click="delDetial(orderDetail, index)">删除</el-button>
              <el-button v-if="!orderDetail.orderNo" type="info" circle @click="delOrderDetail(index)">
                <i class="el-icon-minus"></i>
              </el-button>
            </div>
          </div>
          <div>
            <el-button v-if="nowChanceStau !== 'check'" class="addone" type="info" circle @click="addOrderDetail">
              <i class="el-icon-plus"></i>
            </el-button>
          </div>
          <!-- 汇总 -->
          <div class="w100p xunhuan">
            <el-divider content-position="left">明细合计</el-divider>
            <el-form-item label="总数量 :" prop="totalQuantity" class="w50p">
              <el-input v-model="formData.totalQuantity" disabled placeholder="内容自动填充请勿输入" />
            </el-form-item>
            <!-- <el-form-item label="总重量/kg :" class="w50p">
              <el-input
                v-model="formData.totalWeight"
                disabled
                placeholder="内容自动填充请勿输入"
              />
            </el-form-item>-->
            <!-- <el-form-item label="总体积/L :" class="w50p">
              <el-input
                v-model="formData.totalVolume"
                disabled
                placeholder="内容自动填充请勿输入"
              />
            </el-form-item>-->
            <el-form-item label="价税合计/元 :" prop="totalPrice" class="w50p">
              <el-input v-model="formData.totalPrice" disabled placeholder="内容自动填充请勿输入" />
            </el-form-item>

            <el-form-item label="备注 :" class="w50p">
              <el-input v-model="formData.remarks" type="textarea" row="2" placeholder="请备注" />
            </el-form-item>
            <el-divider v-if="nowChanceStau === 'check'" content-position="left">审核</el-divider>
            <el-form-item v-if="nowChanceStau === 'check'" label="审核状态 :" prop="forderStatus" class="w50p" :rules="[
              {
                required: true,
                message: '审核状态不能为空',
                trigger: 'change',
              },
            ]">
              <el-select v-model="formData.forderStatus" placeholder="请选择审核状态" clearable class="w100p">
                <el-option v-for="(items, indexs) in checkList" :key="indexs" :label="items.name"
                  :value="items.value" />
              </el-select>
            </el-form-item>
            <el-form-item v-if="nowChanceStau === 'check'" label="审批日期 :" prop="forderStatus" class="w50p" :rules="[
              {
                required: true,
                message: '审核日期不能为空',
                trigger: 'change',
              },
            ]">
              <el-date-picker v-model="formData.approvalTime" type="datetime" value-format="yyyy-MM-dd HH:mm"
                placeholder="选择审批时间" class="w100p" />
            </el-form-item>

            <el-form-item v-if="nowChanceStau === 'check'" label="审核人 :" prop="approverName" class="w50p" :rules="[
              {
                required: true,
                message: '审核人不能为空',
                trigger: 'change',
              },
            ]">
              <el-input v-model="formData.approverName" placeholder="请输入审核人" clearable class="w100p" />
            </el-form-item>
          </div>
        </el-form>
        <div v-if="nowChanceStau !== ''" slot="footer" class="dialog-footer">
          <el-button class="zh-button-one" @click="cancel('formData')">取 消</el-button>
          <el-button v-if="forderStatus === 0" class="zh-button-two" type="primary" @click="save('formData')">保
            存</el-button>
        </div>
      </el-dialog>
    </template>
  </MainSlot>
</template>

<script>
import MainSlot from "@/components/MainSlot";
import Pagination from "@/components/Pagination";
import SearchForm from "@/components/SearchForm";
import TableData from "@/components/TableData";
import BtnSlot from "@/components/BtnSlot";
import EnumSlot from "@/components/EnumSlot";

import { mymixin } from "@/utils/mixins";
import supplierApi from "@/api/livestock-manage/purchaseManage/supplier";
import unitApi from "@/api/basic-info-manage/unit-manage";
import materialApi from "@/api/basic-info-manage/agr-source-base-Manage";
import orderApi from "@/api/livestock-manage/purchaseManage/purchaseOrder";
import orderDetailApi from "@/api/livestock-manage/purchaseManage/orderDetail";
import warehouseApi from "@/api/livestock-manage/storage-manage/warehouse-manage";
import addressApi from "@/api/livestock-manage/inventory/address/addressManage";
import nowpagereqquery from "@/api/digtalOperation/production-batch-manage/create-production-batch/index";
import { mapGetters } from "vuex";
export default {
  name: "SheepInformation",
  components: {
    SearchForm,
    TableData,
    Pagination,
    MainSlot,
    BtnSlot,
    EnumSlot,
  },
  mixins: [mymixin],
  data() {
    return {
      selectionList: [], //
      SupplierList: [], //供应商list
      selectIndex: 0,
      total: 100,
      currentPage: 1,
      dataList: [],
      enumList: [
        { label: "未审核", type: 0 },
        { label: "审核通过", type: 1 },
        { label: "审核不通过", type: 2 },
      ],
      btnList: ["add", "delete"],
      formItemList: [
        {
          label: "采购订单编号",
          type: "input",
          param: "orderNo",
          isShow: true,
        },
        {
          selectOptions: [],
          label: "供应商名称",
          type: "select",
          param: "supplierNo",
          multiple: false,
          isShow: true,
        },
        {
          label: "采购员",
          param: "buyerName",
          isShow: true,
          type: "input",
        },
        {
          label: "审批人",
          param: "approverName",
          isShow: true,
          type: "input",
        },
        {
          label: "订单日期",
          param: "orderTime",
          isShow: true,
          type: "date",
        },
      ],
      tableThead: [],
      // selectValue 用于传递select的编号
      formDatalist: [
        {
          type: "input", // input Select Checkbox TimePicker
          prop: "orderNo",
          typeObj: {},
          name: "采购订单编号",
          required: true,
        },
        {
          type: "date",
          prop: "orderTime", // input Select Checkbox TimePicker
          typeObj: {},
          name: "订单日期",
          required: true,
        },
        {
          type: "Select",
          prop: "supplierName",
          selectValue: "supplierNo",
          typeObj: {},
          name: "供应商",
          required: true,
        },
        {
          type: "input", // input Select Checkbox TimePicker
          prop: "buyerName",
          typeObj: {},
          name: "采购员",
          required: true,
        },
        {
          type: "input", // input Select Checkbox TimePicker
          prop: "bankAccount",
          typeObj: {},
          name: "银行账号",
          required: true,
        },
        {
          type: "input", // input Select Checkbox TimePicker
          prop: "bank",
          typeObj: {},
          name: "开户银行",
          required: true,
        },
        {
          type: "input", // input Select Checkbox TimePicker
          prop: "shippingAddress",
          typeObj: {},
          name: "供应商发货地址",
          required: true,
        },
        {
          type: "input", // input Select Checkbox TimePicker
          prop: "approverName",
          typeObj: {},
          name: "审批人",
          required: true,
        },
        {
          type: "TimePicker", // input Select Checkbox TimePicker
          prop: "approvalTime",
          typeObj: {},
          name: "审批日期",
          required: true,
          notSearch: true,
        },
        {
          type: "input", // input Select Checkbox TimePicker
          prop: "totalNumber",
          typeObj: {},
          name: "总件数",
          required: true,
        },
        {
          type: "input", // input Select Checkbox TimePicker
          prop: "totalQuantity",
          typeObj: {},
          name: "总数量",
          required: true,
        },
        {
          type: "input", // input Select Checkbox TimePicker
          prop: "totalPrice",
          typeObj: {},
          name: "价税合计/元",
          required: true,
        },
        {
          type: "input", // input Select Checkbox TimePicker
          prop: "remarks",
          typeObj: {},
          name: "备注",
          // required: true,
          notSearch: true,
        },
      ],

      // =====================下面可能是用不上的，但是不敢删
      searchlist: {},
      tableColumn: [],
      forderStatus: 0,
      selectedStaffList: [],
      addressList: [],
      stordocList: [],
      unitList: [],
      materialList: [],
      checkList: [
        { name: "未审核", value: 0 },
        { name: "审批通过", value: 1 },
        { name: "审批不通过", value: 2 },
      ],
      formData: {
        orderDetailList: [
          {
            address: "",
            arrivalTime: "",
            castUnitNo: "",
            chandlerName: "",
            confirmQuantity: "",
            discount: "",
            discountPrice: "",
            materialNo: "",
            primaryQuantity: "",
            packNum: "",
            price: "",
            stordocNo: "",
            totalPrice: "",
            unitNo: "",
            exchangeRate: "",
            volume: "",
            weight: "",
          },
        ],
      },
      buttonselectlist: [
        { name: "未审核" },
        { name: "审核通过" },
        { name: "审核未通过" },
      ],

      formDatalists: [
        {
          type: "input", // input Select Checkbox TimePicker
          prop: "orderNo",
          typeObj: {},
          name: "采购订单编号",
          required: true,
        },
        {
          type: "TimePicker", // input Select Checkbox TimePicker
          prop: "orderTime",
          typeObj: {},
          name: "订单日期",
          required: true,
        },
        {
          type: "input", // input Select Checkbox TimePicker
          prop: "buyerName",
          typeObj: {},
          name: "采购员",
          required: true,
        },
        {
          type: "Select",
          prop: "supplierName",
          selectValue: "supplierNo",
          typeObj: {},
          name: "供应商",
          required: true,
        },
        {
          type: "input", // input Select Checkbox TimePicker
          prop: "bankAccount",
          typeObj: {},
          name: "银行账号",
          required: true,
        },
        {
          type: "input", // input Select Checkbox TimePicker
          prop: "bank",
          typeObj: {},
          name: "开户银行",
          required: true,
        },
        {
          type: "input", // input Select Checkbox TimePicker
          prop: "shippingAddress",
          typeObj: {},
          name: "供应商发货地址",
          required: true,
        },
        {
          type: "input", // input Select Checkbox TimePicker
          prop: "totalNumber",
          typeObj: {},
          name: "总件数",
          required: true,
        },
      ],
      rules: {},
    };
  },
  computed: {
    ...mapGetters(['codeList']),
  },
  watch: {
    formData: {
      deep: true,
      handler(val) {
        if (val.orderDetailList) {
          val.totalQuantity = sum(
            val.orderDetailList.map((item) => item.confirmQuantity || 0)
          );
          val.totalVolume = sum(
            val.orderDetailList.map((item) => item.volume || 0)
          );
          val.totalWeight = sum(
            val.orderDetailList.map((item) => item.weight || 0)
          );
          val.totalPrice = sum(
            val.orderDetailList.map((item) => item.totalPrice || 0)
          );
          val.totalNumber = sum(
            val.orderDetailList.map((item) => item.packNum || 0)
          );
        }
        function sum(arr) {
          let s = 0;
          for (let i = arr.length - 1; i >= 0; i--) {
            s += parseInt(arr[i]);
          }
          return s;
        }
        // sum(val.orderDetailList.map(item => item.confirmQuantity))
      },
    },
  },
  created() {
    let list = [];
    this.formDatalist.forEach((el) => {
      let obj = {
        isShow: true,
        label: el.name,
      };
      if (el.prop == "completeStatus") {
        obj.slotName = el.prop;
      } else {
        obj.prop = el.prop;
      }

      list.push(obj);
    });
    list.push({
      isShow: true,
      label: "操作",
      slotName: "operation",
      width: "200",
    });
    this.tableThead = list;
    this.search();
    this.getSupplierList();
    this.getMaterialList();
    this.getstordocList();
    this.getAddressList();
    this.getUnitList();
  },
  methods: {
    // 多选方法
    selectionChange(val) {
      this.selectionList = val || [];
    },

    getBtnEvent(flag) {
      console.log(flag, this.selectIndex, 'this.selectIndex');
      if (flag == "add") {
        if (this.selectIndex === 0) {
          this.add();

        } else {
          this.$message.warning("请选择未审核界面");
        }
      } else if (flag == "delete" && this.selectIndex === 0) {
        if (this.selectionList.length > 0) {
          this.handleDelete(this.selectionList);
        } else {
          this.$message.warning("请先选择表单数据项后再删除！");
        }
      } else if (flag == "delete" && this.selectIndex !== 0) {
        this.$message.warning("审核通过不支持删除");
      }
    },
    //获取选中Enum
    getEnumEvent(enumInfo) {
      console.log(enumInfo);
      this.selectIndex = enumInfo.index || 0;
      if (this.selectIndex === 0) {
        this.addActive = true;
      } else {
        this.addActive = false;
      }
      this.currentPage = 1;
      this.forderStatus = this.selectIndex;
      this.search();
    },
    handleCurrentChange(val) {
      console.log(val);
      this.currentPage = val;
      this.getTableDataList();
    },
    changePageSize(pageSize) {
      this.pageSize = pageSize;
      this.getTableDataList();
    },
    completeStatus(e) {
      let obj = { ...e };
      // orderDetailApi.numberQuery(e.orderNo).then((res) => {
      //   this.$set(obj, "orderDetailList", res.data);
      // });
      this.$confirm("确定完成该条数据?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        customClass: "myClass",
      })
        .then(() => {
          obj.completeStatus = true;
          console.log(obj, "===================================");
          orderApi.edit(obj).then((res) => {
            if (res.code === 1) {
              this.$message.success(res.msg);
              this.search();
            } else {
              this.$message.warning(res.msg || "完成失败");
            }
          });
        })
        .catch(() => { });
    },
    // 获取地址
    getAddressList() {
      addressApi.conditionQuery({}).then((res) => {
        if (res.code === 1) {
          this.addressList = res.data;
        }
      });
    },
    // 获取仓库
    getstordocList() {
      warehouseApi.conditionQuery({}).then((res) => {
        if (res.code === 1) {
          this.stordocList = res.data;
        }
      });
    },
    // 获取所有物料
    getMaterialList() {
      materialApi.getqueryList({}).then((res) => {
        if (res.code === 1) {
          let list = res.data || []
          this.materialList = list.filter(item => {
            return !!item.unitNo
          });
        }
      });
    },
    // 获取单位列表
    getUnitList() {
      unitApi.getPlantingUnitListByCondition({}).then((res) => {
        console.log(res.data);
        if (res.code === 1) this.unitList = res.data;
      });
    },
    // 获取供应商
    async getSupplierList() {
      let res = await supplierApi.conditionQuery({});
      if (res.code === 1) {
        let list = [];
        // 提供表头搜索数据
        res.data.forEach((item) => {
          list.push({
            name: item.supplierName,
            value: item.supplierNo,
          });
        });
        this.SupplierList = res.data;
        this.setFormOptions();
        this.formDatalists.forEach((item, index) => {
          if (item.prop === "supplierName") {
            this.$set(this.formDatalists[index], "typeObj", { list: list });
          }
        });
        this.formDatalist.forEach((item, index) => {
          if (item.prop === "supplierName") {
            this.$set(this.formDatalist[index], "typeObj", {
              list: list,
              listName: ["name", "value"],
            });
          }
        });
      }
    },
    setFormOptions() {
      let list = JSON.parse(JSON.stringify(this.formItemList));
      this.formItemList = [];
      list.forEach((item, index) => {
        if (item.param == "supplierNo") {
          let selectOptions = this.SupplierList.map((data) => {
            return {
              text: data.supplierName,
              value: data.supplierNo,
            };
          });
          item.selectOptions = selectOptions;
        }
      });
      this.$nextTick(() => {
        this.$set(this, "formItemList", list);
      });
      console.log(this.formItemList);
    },
    // 获取单个商品
    getGoods(event, index) {
      materialApi.getqueryList({ materialNo: event }).then((res) => {
        this.formData.orderDetailList[index].unitNo = res.data[0].unitNo;
        this.formData.orderDetailList[index].castUnitNo = res.data[0].unitNo;
      });
    },
    // 获取单个供应商
    getCoustomer(event, prop) {
      if (prop === "supplierName") {
        console.log(event, prop);
        supplierApi.conditionQuery({ supplierNo: event }).then((res) => {
          if (res.code === 1) {
            this.$set(this.formData, "bank", res.data[0].bank);
            this.$set(this.formData, "bankAccount", res.data[0].bankAccount);
            this.formData.supplierName = res.data[0].supplierName;
          }
        });
      } else {
        return;
      }
    },
    // 切换
    nowselectbuttonindex(index) {
      this.forderStatus = index;
      console.log(this.forderStatus);
      this.currentPage = 1;
      this.search();
    },
    addOrderDetail() {
      this.formData.orderDetailList.push({
        address: "",
        arrivalTime: "",
        castUnitNo: "",
        chandlerName: "",
        confirmQuantity: 1,
        discount: "",
        discountPrice: "",
        materialNo: "",
        packNum: "",
        price: "",
        primaryQuantity: "1",
        stordocNo: "",
        totalPrice: "",
        unitNo: "",
        exchangeRate: "1",
        volume: "",
        weight: "",
        key: Date.now(),
      });
    },
    delOrderDetail(index) {
      console.log(this.formData.orderDetailList);
      if (this.formData.orderDetailList.length === 1) {
        return;
      } else {
        this.formData.orderDetailList.splice(index, 1);
      }
    },
    getTableDataList() {
      this.loading = true;
      let params = {
        page: this.currentPage,
        size: this.pageSize,
        organizationNo: sessionStorage.organizationNo,
        breedTypeNo: sessionStorage.breedTypeNo,
        entity: {
          forderStatus: this.forderStatus,
          ...this.searchlist,
          startTime: this.searchlist.orderTime
            ? this.searchlist.orderTime + " 00:00:00"
            : "",
          endTime: this.searchlist.orderTime
            ? this.searchlist.orderTime + " 23:59:59"
            : "",
        },
      };
      delete params.entity.orderTime;
      orderApi.pageQuery(params).then((res) => {
        this.loading = false;
        let data = res.data;
        if (data) {
          this.dataList = data.content || [];
          this.total = data.totalElements;
          this.addblankmet();
          this.resetActionBar();
          if (this.forderStatus === 0) {
            this.addActive = true;
          } else {
            this.addActive = false;
          }
        }
      });
    },
    handleSelectionChange(list) {
      this.selectedStaffList = [];
      this.selectedStaffList = list.map((item) => item.orderNo);
      if (this.selectedStaffList.length > 0) this.delActive = true;
      else this.delActive = false;
    },
    delmessage() {
      orderApi
        .numberBatchDel({ noList: this.selectedStaffList })
        .then((res) => {
          if (res.code === 1) {
            this.$message.success(res.msg);
            this.search();
          } else {
            this.$message.warning(res.msg || "删除失败");
          }
        });
    },
    // 计算主数量相关
    countNum(event, index) {
      console.log(event);
      if (
        this.formData.orderDetailList[index].confirmQuantity &&
        this.formData.orderDetailList[index].exchangeRate
      ) {
        this.$set(
          this.formData.orderDetailList[index],
          "primaryQuantity",
          this.formData.orderDetailList[index].confirmQuantity *
          this.formData.orderDetailList[index].exchangeRate
        );
      }
    },
    // 计算价钱相关
    countOnePrice(event, index) {
      if (
        this.formData.orderDetailList[index].confirmQuantity &&
        this.formData.orderDetailList[index].price &&
        this.formData.orderDetailList[index].discount
      ) {
        let a =
          (this.formData.orderDetailList[index].confirmQuantity *
            this.formData.orderDetailList[index].price *
            (10 - this.formData.orderDetailList[index].discount)) /
          10;
        let discountPrice = Math.floor(a * 100) / 100;
        this.formData.orderDetailList[index].discountPrice = discountPrice;
        let b =
          this.formData.orderDetailList[index].confirmQuantity *
          this.formData.orderDetailList[index].price -
          discountPrice;
        this.formData.orderDetailList[index].totalPrice =
          Math.floor(b * 100) / 100;
      } else if (
        this.formData.orderDetailList[index].confirmQuantity &&
        this.formData.orderDetailList[index].price &&
        !this.formData.orderDetailList[index].discount
      ) {
        let b =
          this.formData.orderDetailList[index].confirmQuantity *
          this.formData.orderDetailList[index].price;
        this.formData.orderDetailList[index].totalPrice =
          Math.floor(b * 100) / 100;
        this.formData.orderDetailList[index].discountPrice = "";
      } else {
        this.formData.orderDetailList[index].totalPrice = "";
        this.formData.orderDetailList[index].discountPrice = "";
      }
      this.countNum(event, index);
    },
    handleDelete(list) {
      let selectedStaffList = [];
      list.forEach((item) => {
        selectedStaffList.push(item.orderNo);
      });
      this.$confirm("此操作将永久删除该条数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        customClass: "myClass",
      })
        .then(() => {
          let params = {
            noList: selectedStaffList,
          };
          orderApi.numberBatchDel(params).then((res) => {
            if (res.code === 1) {
              this.$message.success(res.msg);
              this.search();
            } else {
              this.$message.warning(res.msg || "删除失败");
            }
          });
        })
        .catch(() => { });
    },
    add() {
      // 获取订单编号
      nowpagereqquery
        .addcode("ORDER")
        .then((res) => {
          this.$set(this.formData, "orderNo", res.data);
        })
        .catch((err) => {
          this.$message.error(err);
        });
      this.formData = {
        orderDetailList: [
          {
            address: "",
            arrivalTime: "",
            castUnitNo: "",
            chandlerName: "",
            confirmQuantity: "",
            discount: "",
            discountPrice: "",
            materialNo: "",
            packNum: "",
            price: "",
            primaryQuantity: "",
            stordocNo: "",
            totalPrice: "",
            unitNo: "",
            exchangeRate: "",
            volume: "",
            weight: "",
          },
        ],
      };
      this.$set(this.formData.orderDetailList[0], "confirmQuantity", 1);
      this.$set(this.formData.orderDetailList[0], "exchangeRate", 1);
      this.$set(this.formData.orderDetailList[0], "primaryQuantity", 1);
      this.$set(this.formData.orderDetailList[0], "packNum", 1);
      this.nowChanceStau = "add";
      this.titleText = "添加采购订单";
      this.addActive = false;
      this.delActive = false;
      this.dialogFormVisible = true;
    },
    edit(row) {
      this.formData = { ...row };
      orderDetailApi.numberQuery(row.orderNo).then((res) => {
        this.$set(this.formData, "orderDetailList", res.data);
      });
      this.nowChanceStau = "edit";
      this.titleText = "修改采购订单";
      this.dialogFormVisible = true;
      this.addActive = true;
      this.delActive = false;
    },
    check(row) {
      this.formData = { ...row };
      orderDetailApi.numberQuery(row.orderNo).then((res) => {
        this.$set(this.formData, "orderDetailList", res.data);
      });
      this.nowChanceStau = "check";
      this.titleText = "修改订单";
      this.dialogFormVisible = true;
    },
    addDetail(e, index) {
      let validateFieldList = [];
      this.$refs["formData"].validateField(
        [
          "orderDetailList." + index + ".materialNo",
          "orderDetailList." + index + ".confirmQuantity",
          "orderDetailList." + index + ".castUnitNo",
          "orderDetailList." + index + ".unitNo",
          "orderDetailList." + index + ".exchangeRate",
          "orderDetailList." + index + ".primaryQuantity",
          "orderDetailList." + index + ".price",
          "orderDetailList." + index + ".packNum",
          "orderDetailList." + index + ".totalPrice",
          "orderDetailList." + index + ".address",
        ],
        (valid) => {
          if (!valid) {
            validateFieldList.push(valid);
            // 因为我这里总共校验了三个字段,所有最终三个字段都校验成功之后,数组中会有三个""
            if (
              validateFieldList.length === 10 &&
              validateFieldList.every((item) => item === "")
            ) {
              orderDetailApi.add(e).then((res) => {
                if (res.code === 1) {
                  this.$message.success(res.msg);
                  orderDetailApi.numberQuery(e.orderNo).then((res) => {
                    this.$set(this.formData, "orderDetailList", res.data);
                  });
                } else {
                  this.$message.warning(res.msg || "添加失败");
                }
              });
            }
            // 校验不通过走这里
            return;
          } else {
            return false;
          }
        }
      );
    },
    editDetail(e) {
      this.$confirm("确定修改该条数据?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        customClass: "myClass",
      })
        .then(() => {
          orderDetailApi.edit(e).then((res) => {
            if (res.code === 1) {
              this.$message.success(res.msg);
            } else {
              this.$message.warning(res.msg || "修改失败");
            }
          });
        })
        .catch(() => { });
    },
    delDetial(e, index) {
      this.$confirm("此操作将永久删除该条数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        customClass: "myClass",
      })
        .then(() => {
          orderDetailApi.numberQuery(e.orderNo).then((res) => {
            if (res.data.length <= 1) {
              this.$message.warning("已是最后一条数据禁止删除");
            } else {
              orderDetailApi.numberDel(e.orderDetailNo).then((res) => {
                if (res.code === 1) {
                  this.$message.success(res.msg);
                  this.formData.orderDetailList.splice(index, 1);
                } else {
                  this.$message.warning(res.msg || "删除失败");
                }
              });
            }
          });
        })
        .catch(() => { });
    },
    save(formData) {
      this.$refs[formData].validate((valid) => {
        if (valid) {
          if (this.nowChanceStau === "edit") {
            orderApi.edit(this.formData).then((res) => {
              if (res.code === 1) {
                this.$message.success(res.msg || "修改成功！");
                this.dialogFormVisible = false;
                this.search();
                this.$refs[formData].resetFields();
              } else {
                this.$message.error(res.msg || "修改失败！");
              }
            });
          } else if (this.nowChanceStau === "add") {
            orderApi.add(this.formData).then((res) => {
              if (res.code === 1) {
                this.$message.success(res.msg || "新增成功！");
                this.dialogFormVisible = false;
                this.search();
                this.$refs[formData].resetFields();
              } else {
                this.$message.error(res.msg || "新增失败！");
              }
            });
          } else if (this.nowChanceStau === "check") {
            orderApi.edit(this.formData).then((res) => {
              if (res.code === 1) {
                this.$message.success(res.msg || "审核成功！");
                this.dialogFormVisible = false;
                this.search();
                this.$refs[formData].resetFields();
              } else {
                this.$message.error(res.msg || "审核失败！");
              }
            });
          }
        } else {
          return false;
        }
      });
    },
  },
};
</script>
<style scoped lang="scss">
@import "~@/styles/variables.scss";

::v-deep .el-dialog__wrapper .el-dialog .el-form-item .el-form-item__label {
  min-width: 140px;
}

::v-deep .el-dialog__body {
  max-height: 66vh;
  overflow-y: auto;
}

::v-deep .el-form {
  display: flex;
  flex-wrap: wrap;
}

::v-deep .el-form-item__content {
  display: flex;
  margin-right: 20px;
}

.xunhuan {
  margin-top: 20px;
  position: relative;
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;

  .goods {
    font-size: 20px;
    font-weight: bold;
    margin-bottom: 20px;
    text-align: left;
    padding-left: 140px;
  }

  .editBox {
    position: absolute;
    right: 0px;
    bottom: -30px;
  }
}

.addone {
  margin-left: 140px;
}

.zhu {
  display: flex;

  ::v-deep .el-input__inner {
    background-color: rgb(241, 239, 239) !important;
  }

  ::v-deep .el-form-item__content {
    margin-right: 0px;
  }
}

.numberUnit {
  display: flex;

  .one {
    width: 75%;
  }

  .two {
    width: 25%;
  }
}

::v-deep .el-dialog__wrapper .el-dialog .el-form-item .el-form-item__label {
  min-width: 140px;
}

::v-deep .el-form-item[data-v-3d395f82] {
  display: flex;
  margin-bottom: 10px;
  margin-right: 20px;
}

::v-deep .el-dialog__body {
  max-height: 66vh;
  overflow-y: auto;
}

::v-deep .el-form {
  display: flex;
  flex-wrap: wrap;

  .el-form-item__content {
    display: flex;
    margin-right: 20px;
  }
}

.xunhuan {
  margin-bottom: 50px;
  position: relative;
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;

  .goods {
    font-size: 20px;
    font-weight: bold;
    margin-bottom: 20px;
    text-align: left;
    padding-left: 140px;
  }

  .editBox {
    z-index: 100;
    position: absolute;
    right: 0px;
    bottom: -30px;
  }
}

.zhu {
  display: flex;

  ::v-deep .el-input__inner {
    background-color: rgb(241, 239, 239) !important;
  }
}

.numberUnit {
  display: flex;

  .one {
    width: 75%;
  }

  .two {
    width: 25%;
  }
}
</style>
